/*
tool.c
offer some small tools realize
designed by lunanting 

---------------------------
2021-10-08 16:57:14
create file
*/

#include "aos/kernel.h"
#include "tool.h"


/*
get diff ms from start_time
return: diff time
*/
uint64_t get_diff_ms(uint64_t start_time){
    uint64_t diff_ms = 0;
    uint64_t cur_time = aos_now_ms();

    if(cur_time >= start_time){
        diff_ms = cur_time - start_time;
    }else{
        //处理翻转的情况
        diff_ms = 0xFFFFFFFFFFFFFFFFULL - start_time + cur_time;
    }

    return diff_ms;
}

/* binary sem api, added by maoxinfeng */
int binary_sem_new(binary_sem_t *bin_sem)
{
	bin_sem->sem = false;
	return aos_mutex_new(&bin_sem->mutex);
}

void binary_sem_free(binary_sem_t *bin_sem)
{
	bin_sem->sem = false;
	aos_mutex_free(&bin_sem->mutex);
}

void binary_sem_signal(binary_sem_t *bin_sem)
{
	aos_mutex_lock(&bin_sem->mutex, 1000);
	bin_sem->sem = true;
	aos_mutex_unlock(&bin_sem->mutex);
}

bool binary_sem_wait(binary_sem_t *bin_sem, unsigned int timeout)
{
	bool flag = false;

	aos_mutex_lock(&bin_sem->mutex, timeout);
	if(true == bin_sem->sem){
		flag = true;
		bin_sem->sem = false;
	}else{
		flag = false;
	}
	aos_mutex_unlock(&bin_sem->mutex);

	return flag;
}

int binary_sem_is_valid(binary_sem_t *bin_sem)
{
    ksem_t *k_sem;

    if (bin_sem == NULL) {
        return 0;
    }

    k_sem = bin_sem->mutex.hdl;

    if (k_sem == NULL) {
        return 0;
    }

    return 1;
}

//end of the file
